<?php


namespace app\index\controller;

use app\index\model\ActionRole;
use app\index\model\Group;
use app\index\model\NoticeProduct;
use app\index\model\Product;
use app\index\model\StockWarehouse;
use app\index\model\User;
use app\index\model\Vendor;
use think\Db;
use think\Loader;
use think\Request;
use think\Session;

class Goods extends BaseController
{

    protected $request;
    protected $validate;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->request = $request;
        $this->validate = Loader::validate('Goods');
    }

    public function getParam()
    {
        ['status' => $status, 'result' => $result] = StockWarehouse::getStockWarehouseList($this->user_session['group_id']);
        $vendorList = Vendor::getVendorCompanyNameList();
        ['user_list' => $user_list, 'group_list' => $group_list] = User::getUserList();
        return json(['code' => 0, 'stock_warehouse' => $result['stock_warehouse'], 'user_list' => $user_list, 'group_list' => $group_list,'vendor_list'=>$vendorList,'vendor_batch_list'=>$vendorList]);
    }

    public function getList()
    {
        $page = input('post.pageIndex', 1);
        $size = input('post.pageSize', 10);
        $post = input('post.', [], 'trim');
        $search_param = [
            'search_key' => $post['search_key'] ?? null,
            'search_value' => $post['search_value'] ?? null,
            'stock_warehouse' => $post['warehouse'] ?? null,
            'create_time' => $post['create_time'] ?? null,
            'group_id' => $post['group_id'] ?? null,
            'user_id' => $post['user_id'] ?? null,
            'vendor_id'=>$post['vendor_list']??null,
        ];
        $page_param = [
            'page_num' => $page,
            'page_size' => $size,
        ];
        ['status' => $status, 'result' => $result] = Product::getProductList($search_param, $page_param);
        if ($status === false) {
            return json(['code' => 1, 'msg' => $result['msg']]);
        }
        return json(['code' => 0, 'product' => $result['product'], 'pageTotal' => $result['total'], 'action_role' => $result['action_role']]);
    }

    public function getStockInParam()
    {
        ['action_role' => $action_role] = ActionRole::checkUserActionRole('product');
        ['status' => $status, 'result' => $result] = StockWarehouse::getStockWarehouseList($this->user_session['group_id']);
        ['user_list' => $user_list, 'group_list' => $group_list] = User::getUserList();
        $vendorList = Vendor::getVendorCompanyNameList();
        return json(['code' => 0, 'stock_warehouse' => $result['stock_warehouse'], 'user_list' => $user_list, 'group_list' => $group_list, 'vendor_list'=>$vendorList, 'action_role' => $action_role]);
    }

    public function addGoods()
    {
        $data = input('post.data/a');
        $validate_result = $this->validate->scene('create')->check($data);

        if (!$validate_result) {
            return json(['code' => 1, 'msg' => $this->validate->getError()], 200);
        }
        $insert_data = [
            'cn_name' => trim($data['cn_name']),
            'en_name' => trim($data['en_name']),
            'vendor_id' => $data['company']??null,
            'image' => $data['image'],
            'pur_price' => $data['pur_price'],
            'amount' => $data['amount'],
            'warehouse' => $data['warehouse'],
            'type' => $data['type'],
            'weight' => $data['weight'],
            'selling_price' => $data['selling_price'],
            'multiple' => $data['multiple']??1.5,
            'create_user' => $this->user_session['id'],
        ];

        ['status' => $status, 'result' => $result] = Product::addGoods($insert_data);
        if ($status === false) {
            return json(['code' => 1, 'msg' => $result]);
        }
        return json(['code' => 0, 'msg' => $result]);
    }

    /**
     * 批量入库
     * create by yhb on 2021/4/2 11:56
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function createStockBatchIn()
    {
        $data = input('post.data/a');
        $validate_result=$this->validate->scene('create_batch_product')->check($data);
        if(!$validate_result){
            return json(['code'=>1,'msg'=>$this->validate->getError()],200);
        }
        $insert_product=[];
        $insert_product_history=[];
        if (!empty($data)) {
            $cn_name = [];
            $en_name = [];
            foreach ($data['product'] as $k => $v) {
                $insert_product[] = [
                    'cn_name' => trim($v['cn_name']),
                    'en_name' => trim($v['en_name']),
                    'weight' => $v['weight'] ?? '',
                    'selling_price' => $v['selling_price'],
                    'multiple' => $v['multiple']??1.5,
                    'image' => $v['image'],
                    'type' => $v['type'],
                    'pur_price' => $v['pur_price'],
                    'amount' => $v['amount'],
                    'warehouse' => $data['warehouse'],
                    'create_user' => $this->user_session['id']
                ];
                $insert_product_history[] = [
                    'pur_price' => $v['pur_price'],
                    'type' => 1,
                    'amount' => $v['amount'],
                    'create_user' => $this->user_session['id'],
                ];
                $cn_name[] = trim($v['cn_name']);
                $en_name[] = trim($v['en_name']);
            }
        } else {
            return json(['status' => false, 'result' => '请填写需要采购的新品']);
        }
        $obj = Product::field('id,cn_name,en_name')
            ->where('cn_name','in',$cn_name)
            ->whereOr('en_name','in',$en_name)
            ->where('del_flag',0)
            ->where('warehouse',$data['warehouse'])
            ->select();
        if(!empty($obj)){
            $repeat = $obj->toArray();
            if(!empty($repeat)){
                return json(['code'=>1,'msg'=>'商品名已被使用 '.' '.$repeat[0]['cn_name'].' '.$repeat[0]['en_name']]);
            }
        }

        ['status'=>$status,'result'=>$result] = Product::createStockBatchIn($insert_product,$insert_product_history,$data['company']);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    public function getGoodsByGoodsId()
    {
        $id = input('post.id');
        if (!$id) {
            return json(['code' => 1, 'msg' => 'id不能为空']);
        }
        ['status' => $status, 'result' => $result] = Product::getGoodsByGoodsId($id);
        return json(['code' => 0, 'data' => $result['data']]);
    }

    public function getGoodsById()
    {
        $id = input('post.id');
        if (!$id) {
            return json(['code' => 1, 'msg' => 'id不能为空']);
        }
        ['status' => $status, 'result' => $result] = Product::getGoodsById($id);
        if ($status === false) {
            return json(['code' => 1, 'msg' => $result]);
        }
        return json(['code' => 0, 'data' => $result['data']]);
    }

    public function getGoodsByName()
    {
        $warehouse=input('post.warehouse');
        $en_name=input('post.en_name','','trim');
        $cn_name=input('post.cn_name','','trim');
        ['status'=>$status,'result'=>$result]=Product::getGoodsByName($warehouse,$en_name,$cn_name);
        if($status===false){
            return json(['code'=>2,'msg'=>'未找到商品']);
        }
        return json(['code'=>0,'en_name'=>$result['en_name'],'cn_name'=>$result['cn_name'],'id'=>$result['id']]);
    }

    public function getGoodsListByName()
    {
        $cn_name = input('post.cn_name', '');
        $en_name = input('post.en_name', '');
        $group = input('post.group');
        if (!$group) {
            return json(['code' => 1, 'msg' => '请选择组']);
        }
        if (!$cn_name && !$en_name) {
            return json(['code' => 0, 'data' => []]);
        }
        ['status' => $status, 'result' => $result] = Product::getGoodsListByName($group, $cn_name, $en_name);
        if ($status === false) {
            return json(['code' => 1, 'msg' => $result]);
        }
        return json(['code' => 0, 'data' => $result['data']]);
    }

    public function searchGoodsList(){
        $value=input('post.value','');
        if (is_numeric($value)&&$value>0){
            ['status' => $status, 'result' => $result] = Product::getGoodsById($value);
            if ($status === false) {
                ['status' => $status, 'result' => $result] = Product::getGoodsByNames($value);
                if ($status===false){
                    return json(['code' => 1, 'msg' => $result]);
                }
            }
        }else{
            ['status' => $status, 'result' => $result] = Product::getGoodsByNames($value);
            if ($status===false){
                return json(['code' => 1, 'msg' => $result]);
            }
        }
        return json(['code' => 0, 'data' => $result['data']]);
    }

    public function getGoodsListByEnName()
    {
        $en_name = input('post.en_name', '');
        $cn_name = input('post.cn_name', '');

        ['status' => $status, 'result' => $result] = Product::getGoodsListByEnName($en_name,$cn_name);
        if ($status === false) {
            return json(['code' => 1, 'msg' => $result]);
        }
        return json(['code' => 0, 'data' => $result['data']]);
    }

    public function updateGoodsStock()
    {
        $data = input('post.data/a');
        $validate_result = $this->validate->scene('stock_in')->check($data);

        if (!$validate_result) {
            return json(['code' => 1, 'msg' => $this->validate->getError()], 200);
        }
        $update_data = [
            'pur_price' => $data['pur_price'],
            'amount' => $data['amount'],
            'weight' => $data['weight'],
            'create_user' => $this->user_session['id'],
        ];

        ['status' => $status, 'result' => $result] = Product::updateGoodsStock($data['id'], $update_data);
        if ($status === false) {
            return json(['code' => 1, 'msg' => $result]);
        }
        ['status' => $status, 'result' => $result] = Product::lockStockByProduct($data['id']);
        if ($status === false) {
            return json(['code' => 2, 'msg' => '更新库存成功，锁定库存失败', $result]);
        }
        ['status' => $status, 'result' => $result] = Product::demandStockByProduct([$data['id']]);
        if ($status === false) {
            return json(['code' => 2, 'msg' => '更新库存成功，锁定需求库存失败', $result]);
        }

        return json(['code' => 0, 'msg' => '更新库存成功']);
    }

    public function updateGoodsPrice()
    {
        $data = input('post.data/a', []);

        $validate_result = $this->validate->scene('change_price')->check($data);

        if (!$validate_result) {
            return json(['code' => 1, 'msg' => $this->validate->getError()], 200);
        }

        ['status' => $status, 'result' => $result] = Product::updateGoodsPrice($data['id'], $data['selling_price']);
        if ($status === false) {
            return json(['code' => 1, 'msg' => $result]);
        }
        return json(['code' => 0, 'msg' => $result]);
    }

    public function updateGoods()
    {
        $data = input('post.');
        $validate_result = $this->validate->scene('update')->check($data);
        $data['cn_name']=trim($data['cn_name']);
        $data['en_name']=trim($data['en_name']);
        if (!$validate_result) {
            return json(['code' => 1, 'msg' => $this->validate->getError()], 200);
        }
        $repeat=(new Product())->where('id','<>',$data['id'])->where(function ($query)use($data){
            $query->where('cn_name','=',$data['cn_name'])->whereOr('en_name','=',$data['en_name']);
        })->where('del_flag',0)->where('warehouse',$data['warehouse'])->field('id,cn_name,en_name')->find();
        if(!empty($repeat)){
            return json(['code' => 1, 'msg' => '商品名已被使用 '.' '.$repeat['cn_name'].' '.$repeat['en_name']]);
        }
        $result = (new Product())->save(['cn_name' => $data['cn_name'], 'en_name' => $data['en_name'],'remark'=>$data['remark'],'introduction'=>$data['introduction'],'vendor_id'=>$data['vendor_id'], 'image' => $data['image'],'multiple'=>$data['multiple']??1.5], ['id' => $data['id']]);
        if ($result === false) {
            return json(['code' => 1, 'msg' => '更新失败']);
        }
        return json(['code' => 0, 'msg' => '更新成功']);
    }

    /**
     * 展示商品
     * create by yhb on 2021/3/26 14:03
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exhibitionProduct()
    {
        $product_id = input('post.id');

        $productClass = new Product();

        ['status'=>$status,'result'=>$result]=$productClass->exhibitionProduct(['id'=>$product_id]);
        if($status===false){
            return json(['code'=>1,'msg'=>$result]);
        }
        return json(['code'=>0,'msg'=>$result]);
    }

    /**
     * 批量更新供应商
     * create by yhb on 2021/3/31 11:59
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateProductAll()
    {
        $data = input('post.data/a');
        $productClass = new Product();
        ['status'=>$status,'result'=>$result]=$productClass->updateProductAll($data);
        if($status===0){
            return json(['status'=>1,'msg'=>$result]);
        }
        return json(['status'=>0,'msg'=>$result]);
        
    }

    public function getMark()
    {
        $marks=Db::name('mark')->where('del_flag',0)->column('mark_text','id');
        return json(['status'=>0,'marks'=>$marks]);
    }

    public function addMark()
    {
        $pid=input('post.pid/a');
        $mark=input('post.marks/a');
        if (empty($pid)){
            return json(['status'=>1,'msg'=>'请选择商品']);
        }
        ['status'=>$status,'result'=>$result]=Product::addMark($pid,$mark);
        if($status===false){
            return json(['status'=>1,'msg'=>$result]);
        }
        return json(['status'=>0,'msg'=>$result]);
    }

}